// 基于Element Plus定义的表单校验规则
import * as regExpConst from '@/utils/regExpConst'
import type { FormRules } from 'element-plus'

export const userRules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    {
      validator: validateUsername,
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 5,
      max: 15,
      message: '密码应该在5~15位',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    },
    {
      validator: validateEmail,
      trigger: 'blur'
    }
  ],
  idCard: [
    {
      required: true,
      message: '请输入身份证号',
      trigger: 'blur'
    },
    {
      validator: validateIdCard,
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      validator: validatePhone,
      trigger: 'blur'
    }
  ],
  userIncome: [
    {
      required: true,
      message: '请输入您的具体收入',
      trigger: 'blur'
    },
    {
      type: 'number',
      message: '请收入正确的收入数字'
    }
  ],
  nickname: [
    {
      required: true,
      message: '请输入昵称',
      trigger: 'blur'
    }
  ]
}

function validateUsername(rule: any, value: any, callback: any) {
  if (regExpConst.USERNAME_REG_EXP.test(value)) {
    callback()
  } else {
    callback(new Error('只能由数字、字母组成，且必须在8~10位'))
  }
}

function validateEmail(rule: any, value: any, callback: any) {
  if (regExpConst.EMAIL_REG_EXP.test(value)) {
    callback()
  }else {
    callback(new Error('请输入正确的邮箱'))
  }
}

function validateIdCard(rule: any, value: any, callback: any) {
  if (regExpConst.ID_CARD_REG_EXP.test(value)) {
    callback()
  }else {
    callback(new Error('请输入正确的身份证号'))
  }
}

function validatePhone(rule: any, value: any, callback: any) {
  if (regExpConst.PHONE_NUMBER_REG_EXP.test(value)) {
    callback()
  }else {
    callback(new Error('请输入正确的手机号码'))
  }
}